package com.mmche.web.controller;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.easycoding.framework.annotation.Token;
import com.framework.base.util.CookieUtil;
import com.framework.base.util.StringTools;
import com.framework.base.util.Tool;
import com.framework.support.domain.PageMan;
import com.framework.ums.common.CommonService;
import com.framework.web.springmvc.BaseController;
import com.mmche.base.pojo.Attract;
import com.mmche.base.pojo.Brand;
import com.mmche.base.pojo.Models;
import com.mmche.base.service.AttractService;
import com.mmche.base.service.BrandService;
import com.mmche.base.service.LinksService;
import com.mmche.base.service.ModelsService;
import com.mmche.base.service.OnlineContentService;
import com.mmche.car.pojo.Car;
import com.mmche.car.service.CarService;
import com.mmche.common.Constant;
import com.mmche.common.Util;
import com.mmche.sell.pojo.SellComment;
import com.mmche.sell.service.SellCommentService;
import com.mmche.stock.service.AncillaService;

@Controller
public class HomeController extends BaseController{
	
	@Resource(name="webCarService")
	private CarService carService;
	
	@Resource(name="webBrandService")
	private BrandService brandService;
	
	@Resource
	private ModelsService modelsService;
	
	@Resource(name="webOnlineContentService")
	private OnlineContentService onlineContentService;
	
	@Resource
	private LinksService linksService;
	
	@Resource
	private SellCommentService sellCommentService;
	
	@Resource 
	private AttractService attractService;
	
	@Resource
	private AncillaService ancillaService;

	@RequestMapping("/")
	private String home(){
		return "forward:/index.html";
	}
	
	@RequestMapping("/index.html")
	private String index(Map<String,Object> returnValue){
		returnValue.put("location", "home");
		returnValue.put("brands", this.brandService.getCarBrands());
		returnValue.put("hotBrands",this.brandService.getIndexBrands());
		returnValue.put("carTypes",CommonService.getInstance().getDics(Constant.DIC_CAR_TYPE));
		Map<String,Object> map = new HashMap<String,Object>();
		//促销车辆
		map.put("status", Car.STATUS_SHELVES);
	    map.put("promo", true);
	    returnValue.put("promoCars",this.carService.getCarPageByMap(map, 0, 100));
	    map = new HashMap<String,Object>();
	    //准新车
		map.put("status", Car.STATUS_SHELVES);
		Date maxDate = Tool.dateAddYear(new Date(), -3);
		SimpleDateFormat df = new SimpleDateFormat("yyyy");
		map.put("startYear", df.format(maxDate));
		returnValue.put("newCars",this.carService.getCarPageByMap(map, 0, 6));
		map = new HashMap<String,Object>();
		map.put("status", Car.STATUS_SHELVES);
		map.put("endPrice", String.valueOf(10));
		//经济型
		returnValue.put("lowPriceCars",this.carService.getCarPageByMap(map, 0, 6));
		map = new HashMap<String,Object>();
		map.put("status", Car.STATUS_SHELVES);
		map.put("keywords", "类型:SUV");
		//SUV
		returnValue.put("suvCars",this.carService.getCarPageByMap(map, 0, 6));
		int year =Integer.parseInt(Tool.dateToString(new Date(),"yyyy"));
		List<Integer> yearList = new ArrayList<Integer>();
		for(int i=0;i<11;i++){
			yearList.add(year-10+i);
		}
		returnValue.put("yearList",yearList);
		PageMan page = new PageMan();
	    page.setPageSize(6);
	    PageMan pageMan = new PageMan();
		pageMan.setPageSize(3);
		//交易评价车辆
		returnValue.put("saledCars",this.carService.getSaledCarPage(pageMan));
	    //最新资讯
		returnValue.put("guides",this.onlineContentService.getNewContents(6));
	    //最新攻略
		returnValue.put("news",this.onlineContentService.getNews(page));
	    //友情链接
		returnValue.put("links",this.linksService.findIndexLinks());
		returnValue.put("currentTime", System.currentTimeMillis());
		return "home/index";
	}
	
	/**
	 * 获取品牌车系
	 * @return
	 */
	@RequestMapping("/getSeries/{brandSpell}")
	public @ResponseBody List<Models> search(@PathVariable String brandSpell){
		Brand brand = this.brandService.findBySpell(brandSpell);
		List<Models> list = this.modelsService.getModels(brand.getId());
		return list;
	}
	
	
	/**
	 * 获取估价品牌
	 * @return
	 */
	@RequestMapping("/getEvaluateBrands")
	public @ResponseBody Map<String,String> getEvaluateBrands(){
		try{
			String result = Util.getEvaluateBrands();
			JSONArray brands = JSONArray.fromObject(result);
			Map<String,String> brandMap = new HashMap<String,String>();
			if(!Tool.isEmpty(brands)){
				for(Object brand : brands){
					brandMap.put(StringTools.convert(brand.toString())+ " " + brand.toString(),brand.toString());
				}
				Map<String,String> treemap = new TreeMap<String,String>(brandMap);  
				HttpServletResponse response=this.getWebApplicationContext().getResponse();
				java.util.Date date = new java.util.Date();    
				response.setDateHeader("Last-Modified",date.getTime()); //Last-Modified:页面的最后生成时间 
				response.setDateHeader("Expires",date.getTime()+1000*60*60*24); //Expires:过时期限值 24小时
				response.setHeader("Cache-Control", "public"); //Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息；
			    return treemap;
			}
		}
		catch (Exception e){
    		logger.error("获取品牌列表出错",e);
    	}
		return null;
	}
	
	/**
	 * 获取评估车系
	 * @return
	 */
	@RequestMapping("/getEvaluateSeries/{id}")
	public @ResponseBody JSONObject getEvaluateSeries(@PathVariable String id){
		try{
			if(!Tool.isEmpty(id))
				id = java.net.URLDecoder.decode(id,"UTF-8");
			String result = Util.getEvaluateSeries(id);
			return JSONObject.fromObject(result);
		}
	    catch (Exception e){
    		logger.error("获取车系列表出错",e);
    	}
		return null;
	}
	
	/**
	 * 获取估价排量
	 * @param id
	 * @return
	 */
	@RequestMapping("/getEvaluateDisplacements/{id}")
	public @ResponseBody JSONArray getEvaluateDisplacements(@PathVariable String id){
		try{
			String result = Util.getEvaluateDisplacements(id);
			return JSONArray.fromObject(result);
		}
	    catch (Exception e){
    		logger.error("获取排量列表出错",e);
    	}
		return null;
	}
	
	/**
	 * 友情链接
	 * @param returnValue
	 * @return
	 */
	@RequestMapping("/links.html")
	public String links(Map<String,Object> returnValue){
		returnValue.put("links", this.linksService.findBackLinks());
		return  "home/friend-links";
	}
	
	/**
	 * 车友评价
	 * @param param
	 * @param returnValue
	 * @return
	 */
	@RequestMapping("/comment/{param}")
	private String comment(@PathVariable String param,Map<String,Object> returnValue){
		PageMan pageMan = new PageMan();
		pageMan.setPageSize(15);
		if(param.equals("all"))
			pageMan.setPageNo(1);
		else
			pageMan.setPageNo(Integer.parseInt(param.substring(1)));
		returnValue.put("saledCars",this.carService.getSaledCarPage(pageMan));
		returnValue.put("pageMan", pageMan);
		//限时特卖
		Map<String,Object> map = new HashMap<String,Object>();
		//促销车辆
		map.put("status", Car.STATUS_SHELVES);
	    map.put("promo", true);
	    returnValue.put("promoCars",this.carService.getCarPageByMap(map, 0, 5));
		//浏览记录
	    HttpServletRequest request = this.getWebApplicationContext().getRequest();
		Cookie cookie = CookieUtil.getCookie(request, "viewdHistory");
		if(cookie != null){
			String history = cookie.getValue();
			String[] cars = history.split(",");
			returnValue.put("viewdCars",this.carService.findViewdCar(cars,4));
		}
		return "home/comments";
	}
	
	/**
	 * 车友评价
	 * @return
	 */
	@RequestMapping("/comment.html")
	@Token(create = true)
	public String comment(){
		return "home/comment";
	}
	
	/**
	 * 保存交易评价
	 * @return
	 */
	@RequestMapping("/comment/save.html")
	@Token(validate = true)
	public String saveComment(SellComment comment){
		try{
			sellCommentService.save(comment);
		}
		catch(Exception e){
			logger.error("保存交易评价出错!",e);
		}
		return "redirect:/comment/success.html";
	}
	
	/**
	 * 交易评价成功
	 * @return
	 */
	@RequestMapping("/comment/success.html")
	public String commentSuccess(){
		return "home/comment_result";
	}
	
	/**
	 * 招商流程
	 * @return
	 */
	@RequestMapping("/attract.html")
	@Token(create = true)
	public String attract(){
		return "home/attract";
	}
	
	/**
	 * 保存招商意向
	 * @return
	 */
	@Token(validate = true)
	@RequestMapping("/attract/save.html")
	public String saveAttract(Attract attract){
		try{
			attractService.save(attract);
		}
		catch(Exception e){
			logger.error("保存交易评价出错!",e);
		}
		return "redirect:/attract/success.html";
	}
	
	/**
	 * 保存招商意向流程成功
	 * @return
	 */
	@RequestMapping("/attract/success.html")
	public String attractSuccess(){
		return "/home/attract_result";
	}
	
	@RequestMapping("/ancilla.html")
	public String ancilla(Map<String,Object> returnValue){
		PageMan pageMan = new PageMan();
		pageMan.setPageSize(20);
		pageMan.setPageNo(1);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("show", true);
		returnValue.put("ancillas", ancillaService.getCarPageByMap(map, pageMan));
		return "/home/ancilla";
	}
}

